<?php

namespace MoChat\App\Statistic\Action\FollowUp;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Arr;
use MoChat\App\Client\Constants\ClientFollowRecordTypeCode;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 跟进统计
 * @Controller
 */
class TotalNumber extends AbstractAction
{
    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticFollowUp/total", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $wechatFollowUpNumber = $this->follow($data, ClientFollowRecordTypeCode::WECHAT);//企业微信跟进数
        $callFollowUpNumber = $this->follow($data, ClientFollowRecordTypeCode::PHONE);//呼叫跟进家数
        $interviewFollowUpNumber = $this->follow($data, ClientFollowRecordTypeCode::INTERVIEW);//面访家数
        return [
            "wechatFollowUpNumber" => $wechatFollowUpNumber,
            "callFollowUpNumber" => $callFollowUpNumber,
            "interviewFollowUpNumber" => $interviewFollowUpNumber,
            "totalFollowUpNumber" => $wechatFollowUpNumber + $callFollowUpNumber + $interviewFollowUpNumber
        ];
    }

    /**
     * @param $data
     * @param $type
     * @return int
     */
    private function follow($data, $type): int
    {
        return Db::table('client_follow_record as follow')
            ->leftJoin('work_employee as employee', 'employee.id', '=', 'follow.user_id')
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('follow.followed_at', [$data['startTime'], $data['endTime']]);
            })
            ->where('follow.type', $type)
            ->count(Db::raw('DISTINCT mc_follow.client_id'));
    }

    /**
     * @param $data
     * @return int
     */
    private function interviewFollow($data): int
    {
        return Db::table('client_follow_record as follow')
            ->leftJoin('work_employee as employee', 'employee.id', '=', 'follow.user_id')
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('follow.followed_at', [$data['startTime'], $data['endTime']]);
            })
            ->where('follow.type', ClientFollowRecordTypeCode::INTERVIEW)
            ->count(Db::raw('DISTINCT mc_follow.client_id'));
    }
}
